package com.test.exception;

import java.io.Serializable;

/**
 * 通用结果返回封装
 *
 * @param <T>
 */
public class Result<T> implements Serializable {
    private int code;
    private String msg;
    private T data;

    public Result(T data) {
        this.code = 0;
        this.msg = "success";
        this.data = data;
    }

    public Result(CodeMsg codeMsg) {
        if (codeMsg == null) {
            return;
        }
        this.code = codeMsg.getCode();
        this.msg = codeMsg.getMsg();
    }

    public int getCode() {
        return code;
    }

//    public void setCode(int code) {
//        this.code = code;
//    }
    public Result<T> setCode(int code){
        this.code = code;
        return this;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "Result{" +
                "code=" + code +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                '}';
    }

    /**
     * 成功时返回
     *
     * @param data
     * @param <T>
     * @return
     */
    public static <T> Result<T> success(T data) {
        return new Result<T>(data);
    }

    /**
     * 失败时返回
     *
     * @param codeMsg
     * @param <T>
     * @return
     */
    public static <T> Result<T> fail(CodeMsg codeMsg) {
        return new Result<T>(codeMsg);
    }
}
